package com.itheima.mp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.itheima.mp.domain.dto.UserFormDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Api(tags = "用户管理接口")
@RequiredArgsConstructor
@RestController
@RequestMapping("users")
public class UserController {

    @Autowired
    private UserService userService;


    @GetMapping
    public List<UserVO> list(){
        List<User> users = userService.list();
        return BeanUtil.copyToList(users, UserVO.class);
    }


    @GetMapping("{id}")
    public UserVO getById(@PathVariable("id")Long id){
        return userService.getUserWithAddressById(id);
    }

    private AtomicInteger userCount = new AtomicInteger(0);
    /**
     * 什么是 线程安全问题？
     * 多线程 并发 写 共享资源
     * */
    @PostMapping
    public String add(@RequestBody UserFormDTO dto){
        userService.save(BeanUtil.copyProperties(dto, User.class));
        userCount.incrementAndGet();//++i
        userCount.getAndIncrement(); //i++
        return "success";
    }

    @PutMapping
    public String update(@RequestBody UserFormDTO dto){
        userService.updateById(BeanUtil.copyProperties(dto, User.class));
        return "success";
    }

    @DeleteMapping("{id}")
    public String delete(@PathVariable("id")Long id){
        userService.removeById(id);
        return "success";
    }

    @PutMapping("{id}/deduction/{money}")
    @ApiOperation("扣减用户余额")
    public void freezeUser(@PathVariable("id") Long id, @PathVariable("money")Integer money){
        userService.deduct(id, money);
    }

    @GetMapping("/list")
    @ApiOperation("多条件查询")
    public List<UserVO> queryUsers(UserQuery query){
        return userService.queryUsers(query);
    }
}